Page({
  data: {
    email: '',
    verificationCode: '',
    newPassword: '',
    confirmNewPassword: '',
    countdown: 0,
    isCounting: false
  },

  // 输入邮箱
  inputEmail(e) {
    this.setData({
      email: e.detail.value
    })
  },

  // 输入验证码
  inputVerificationCode(e) {
    this.setData({
      verificationCode: e.detail.value
    })
  },

  // 输入新密码
  inputNewPassword(e) {
    this.setData({
      newPassword: e.detail.value
    })
  },

  // 输入确认新密码
  inputConfirmNewPassword(e) {
    this.setData({
      confirmNewPassword: e.detail.value
    })
  },

  // 发送验证码
  sendVerificationCode() {
    const { email, isCounting } = this.data

    if (isCounting) return

    // 验证邮箱
    const emailRegex = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    if (!emailRegex.test(email)) {
      wx.showToast({
        title: '请输入有效的邮箱地址',
        icon: 'none'
      })
      return
    }

    // 模拟发送验证码
    this.setData({
      isCounting: true,
      countdown: 60
    })

    wx.showToast({
      title: '验证码发送成功',
      icon: 'success'
    })

    // 倒计时
    const timer = setInterval(() => {
      let { countdown } = this.data
      countdown--

      if (countdown <= 0) {
        clearInterval(timer)
        this.setData({
          isCounting: false,
          countdown: 0
        })
      } else {
        this.setData({
          countdown
        })
      }
    }, 1000)
  },

  // 提交找回密码
  submitResetPassword() {
    const { email, verificationCode, newPassword, confirmNewPassword } = this.data

    // 验证表单
    if (!email || !verificationCode || !newPassword || !confirmNewPassword) {
      wx.showToast({
        title: '请填写所有字段',
        icon: 'none'
      })
      return
    }

    if (newPassword !== confirmNewPassword) {
      wx.showToast({
        title: '两次密码不一致',
        icon: 'none'
      })
      return
    }

    if (newPassword.length < 6) {
      wx.showToast({
        title: '密码长度不能少于6位',
        icon: 'none'
      })
      return
    }

    // 模拟找回密码请求
    wx.showLoading({
      title: '处理中...',
    })

    setTimeout(() => {
      wx.hideLoading()

      wx.showToast({
        title: '密码重置成功',
        icon: 'success'
      })

      // 跳转到登录页面
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
    }, 1000)
  },

  // 返回登录
  goBack() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  onLoad: function () {
  }
})